package com.sysd.server;

import com.sysd.server.code.MessageDecode;
import com.sysd.server.code.MessageEncode;
import com.sysd.server.handler.Auth1Handler;
import com.sysd.server.handler.base.AbstractMessageHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: bsh
 * @date: 2025/6/5 09:28
 */
@Component
@RequiredArgsConstructor
public class WebSocketChannelInitializer extends ChannelInitializer<SocketChannel> {

    @SuppressWarnings("rawtypes")
    private final AbstractMessageHandler[] handlers;

    private final Auth1Handler auth1Handler;
//    private final AuthHandler authHandler;

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();
        pipeline.addLast(new LoggingHandler(LogLevel.DEBUG));
        // http decoder
        pipeline.addLast(new HttpServerCodec());
        pipeline.addLast(new MessageEncode());
        pipeline.addLast(new MessageDecode());
        // write in block
        pipeline.addLast(new ChunkedWriteHandler());
        // maximum length of each section
        pipeline.addLast(new HttpObjectAggregator(8192));
        pipeline.addLast(new IdleStateHandler(10, 10, 10, TimeUnit.MINUTES));
        pipeline.addLast(auth1Handler);
        pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
        // my websocket handler
//        pipeline.addLast(authHandler);
        pipeline.addLast(handlers);
    }
}
